<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Order extends MY_Controller {

	function Order()
	{
		parent::MY_Controller();
        $this->load->helper('page');
	}

	function buy($id=''){
		if (!$id) {
			parent::redirect('必须选中产品才可以下单',site_url(),3);
		}
        $user = parent::get_session_value('user');
		page_common();
		$this->load->model('mproduct');
		$info = $this->mproduct->get_product_info($id);
		if (!$info) {
			parent::redirect('你所选的项目不存在',site_url(),3);
		}
		$this->load->model('Mgames');
		$game_areas = $this->Mgames->get_game_areas();
		$this->load->model('Morders');
		do {
			$orderid = self::_get_order_id();
		} while ($this->Morders->check_orderid_available($orderid));
		$groups 	= $this->Mgames->get_groups();
		$careers 	= $this->Mgames->get_careers();
        $games      = $this->Mgames->get_games();
		$this->template->view('v1/order',array('info'=>$info,'game_areas'=>$game_areas,'orderid'=>$orderid,'groups'=>$groups,'careers'=>$careers,'games'=>$games,'username'=>$user['username']));
	}

	function confirm(){
		$post = array('order_id','product','game_id','price','game_area','game_server','role_group','role_career','role_name','role_lvl','uid','tel','qq','comment');
		foreach($post as $val){
			$$val = $this->input->post($val);
		}
		if(!$game_area || !$game_server || !$role_group || !$role_career || !$role_name || !$role_lvl){
			parent::redirect('你的订单信息不完整，请返回重新填写！','back',3);
		}

		$order = array();
		foreach($post as $val){
			$order[$val] = $$val;
		}
		$order['discount'] = 0;
		$order['real_price'] = $order['price'];

		$this->load->model('mproduct');
		$info = $this->mproduct->get_product_info($product);

		$this->load->model('Mmember');
    	if($this->Mmember->check_user_exist($uid)){
    		$dis_utypes = $this->config->item('discount_utypes');
    		if(in_array(substr(strtoupper($uid),0,2),$dis_utypes)){
    			$order['discount'] = $info['discount'];
    			$order['real_price'] = $info['price']-$info['discount'];
    		}
    	}
        //$order['real_price'] = 0.01;
		page_common();
		parent::set_session_value('order',$order);

        $this->load->model('Mgames');
		$group  = $this->Mgames->get_group_info('en_name',$role_group,'cn_name');
		$career = $this->Mgames->get_career_info('en_name',$role_career,'cn_name');
		$area   = $this->Mgames->get_area_name($game_area);
		$server = $this->Mgames->get_server_name($game_server);
		$this->template->assign_array($order);
		$this->template->view('v1/order_confirm',array('info'=>$info,'group'=>$group,'career'=>$career,'area'=>$area,'server'=>$server));
	}

	function modify(){
		$order = parent::get_session_value('order');
		if(!$order) {
			parent::redirect('你的订单已经过期，请返回重新选择！',base_url(),3);
		}
		page_common();
		$this->load->model('mproduct');
		$info = $this->mproduct->get_product_info($order['product']);
        $this->load->model('Mgames');
        $games      = $this->Mgames->get_games();
		$groups 	= $this->Mgames->get_groups($order['game_id']);
		$careers 	= $this->Mgames->get_careers($order['game_id']);
		$areas      = $this->Mgames->get_game_areas($order['game_id']);
		$servers    = $this->Mgames->get_game_servers($order['game_area']);
		$this->template->assign_array($order);
		$this->template->view('v1/order_modify',array('info'=>$info,'groups'=>$groups,'careers'=>$careers,'areas'=>$areas,'servers'=>$servers,'games'=>$games));
	}

	function make(){
		$order = parent::get_session_value('order');
		if($order === FALSE) {
			parent::redirect('你的订单已经过期，请返回重新购买！',base_url(),3);
		}
		$order['order_state'] 	= 1;
		$order['pay_state']		= 0;
		$order['pay_count']		= 0;
		$order['order_time']	= date('Y-m-d H:i:s');
		$this->load->model('Morders');
		if ($this->Morders->insert_new_order($order)) {
			$this->load->model('Mproduct');
			$this->Mproduct->update_pro_times($order['product']);
			log_common('order','order.php','make','order make succ',$order);
			//parent::unset_session_value('order');
			redirect(base_url().'order/pay/');
		} else {
			log_common('order','order.php','make','order make fail',$order);
			//log later
		}
	}

	function pay(){
		$order = parent::get_session_value('order');
		if($order === FALSE) {
			parent::redirect('你的订单已经过期，请返回重新购买！',base_url(),3);
		}
		page_common();
		$info = self::_get_order_info($order['order_id']);
		$this->template->view('v1/order_done',array('order'=>$info));
	}

	function search($offset=0,$word=''){
        page_common();
        if($this->input->post('action') == 'search') {
            $type = $this->input->post('type');
            $word = $this->input->post('word');
            self::_display_search($type,$word,$offset);
            return;
        }
        if($word === '') {
            self::latest($offset);
            return;
        }
	}

	function latest($offset=0){
		page_common();
        $this->load->helper('common');
		$this->load->model('Morders');

		$total = $this->Morders->get_order_count();

		$this->load->library('pagination');

		$config['base_url'] = base_url().'order/latest/';
		$config['total_rows'] = $total;
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['full_tag_open'] = '<div class="pagebar">';
		$config['full_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<span class="current">';
		$config['cur_tag_close'] = '</span>';
		$config['first_link'] = '&#171;';
		$config['last_link'] = '&#187;';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

		$temps = $this->Morders->get_latest_orders($offset,$config['per_page']);
        $orders = array();
        if(is_array($temps) && count($temps)) {
            foreach($temps as $temp){
                $orders[] = get_order_info($temp['order_id']);
            }
        }
        //print_r($orders);exit;
		$this->template->view('v1/order_latest',array('orders'=>$orders,'page_html'=>$page_html));
	}

    /**
     * 我的订单
     * @param <type> $offset
     */
    function my($offset=0){
        $user = parent::get_session_value('user');
        if(!$user){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        page_common();
        $this->load->model('Morders');
        $total = $this->Morders->get_member_order_count($user['username']);

		$this->load->library('pagination');

		$config['base_url'] = base_url().'order/my/';
		$config['total_rows'] = $total;
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['full_tag_open'] = '<div class="pagebar">';
		$config['full_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<span class="current">';
		$config['cur_tag_close'] = '</span>';
		$config['first_link'] = '&#171;';
		$config['last_link'] = '&#187;';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

        $orders = $this->_get_my_orders($user['username']);
        $this->template->view('v1/order_my',array('orders'=>$orders,'page_html'=>$page_html));
    }

    function history($offset=0){
    	$user = parent::get_session_value('user');
        if(!$user){
            parent::redirect('你还未登录，请先登录', base_url(), 3);
        }
        page_common();
        $this->load->model('Morders');
        $total = $this->Morders->get_history_order_count($user['username']);

		$this->load->library('pagination');

		$config['base_url'] = base_url().'order/my/';
		$config['total_rows'] = $total;
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['full_tag_open'] = '<div class="pagebar">';
		$config['full_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<span class="current">';
		$config['cur_tag_close'] = '</span>';
		$config['first_link'] = '&#171;';
		$config['last_link'] = '&#187;';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

        $orders = $this->_get_history_orders($user['username']);
        $this->template->view('v1/order_history',array('orders'=>$orders,'page_html'=>$page_html));
    }

    /**
     * 撤销订单
     * 此操作只有在订单状态为1（尚未付款）时可以执行
     * @param <type> $order_id
     */
    function cancel($order_id=''){
        if ($order_id == ''){
            parent::redirect('必须选中订单方可操作','back');
        }
        parent::check_user_login();
        $info = self::_get_order_info($order_id);
        if($info['order_state'] != 1){ //订单状态不为1
            parent::redirect('订单已经无法取消，你可以联系客服人员！','back');
        }
        $data = array('order_state'=>'-1');
        $this->load->model('Morders');
        if($this->Morders->update_order_data($order_id,$data)){
            parent::redirect('订单成功取消。',base_url().'order/my/');
        } else {
            parent::redirect('订单无法取消，你可以返回重试！','back');
        }
    }

    /**
     * 订单详情
     * @param <type> $order_id
     */
    function detail($order_id){
        if ($order_id == ''){
            parent::redirect('必须选中订单方可操作','back');
        }
        parent::check_user_login();
        $info = self::_get_order_info($order_id);
        page_common();
        $this->template->view('v1/order_detail',array('info'=>$info));
    }

    function _get_my_orders($uid,$limit=10,$offset=0){
        $this->load->model('Morders');
        $res = $this->Morders->get_member_order($uid,$limit,$offset);
        //print_r($res);exit;
        $user_info = $this->Mmember->get_user_info('username',$uid);
        $orders = array();
        $this->load->helper('common');
        //print_r($res);
        if(is_array($res) && count($res)) {
            foreach($res as $temp){
                if($uid == $temp['dai']){
                    $order = get_member_order_info($temp['order_id'],1);
                } else {
                    $order = get_member_order_info($temp['order_id']);
                }
                $this->load->helper('common');
                $order['member_discount'] = get_discount($uid,$order['order_id']);
                $orders[] = $order;
            }
        }
        return $orders;
    }

	function _get_history_orders($uid,$limit=10,$offset=0){
        $this->load->model('Morders');
        $res = $this->Morders->get_history_order($uid,$limit,$offset);
        $user_info = $this->Mmember->get_user_info('username',$uid);
        $this->load->helper('common');
        $orders = array();
        if(is_array($res) && count($res)) {
            foreach($res as $temp){
                $order = get_member_order_info($temp['order_id']);
                $order['member_discount'] = get_discount($uid,$order['order_id']);
                $orders[] = $order;
            }
        }
        return $orders;
    }

    function _display_search($type,$word,$offset=0) {
        $this->load->model('Morders');

        $this->load->helper('common');

        $total = $this->Morders->get_search_count2($type,$word);

		$this->load->library('pagination');

		$config['base_url'] = base_url().'order/search/';
		$config['total_rows'] = $total;
		$config['per_page'] = 20;
		$config['uri_segment'] = 3;
		$config['num_links'] = 3;
		$config['full_tag_open'] = '<div class="pagebar">';
		$config['full_tag_close'] = '</div>';
		$config['cur_tag_open'] = '<span class="current">';
		$config['cur_tag_close'] = '</span>';
		$config['first_link'] = '&#171;';
		$config['last_link'] = '&#187;';
		$config['next_link'] = '&gt;';
		$config['prev_link'] = '&lt;';

		$this->pagination->initialize($config);

		$page_html = $this->pagination->create_links();

        $temps = $this->Morders->get_search_result($type,$word,$offset);

        $orders = array();
        if(is_array($temps) && count($temps)) {
            foreach($temps as $temp){
                $orders[] = get_order_info($temp['order_id']);
            }
        }
        //print_r($orders);exit;
		$this->template->view('v1/order_search',array('orders'=>$orders,'page_html'=>$page_html));
    }

    function _get_order_info($order_id) {
        $this->load->model('Morders');
        $info = $this->Morders->get_order_info($order_id);
        $info['order_discount'] = self::_get_order_discount($order_id);
        $this->load->model('Mproduct');
        $p_info = $this->Mproduct->get_product_info($info['product']);
        if(!empty($p_info)){
            $info['p_name'] = $p_info['p_name'];
            $info['p_days'] = $p_info['p_days'];
            $info['week_num'] = $p_info['week_num'];
            $info['week_money'] = $p_info['week_money'];
        } else {
            $info['p_name'] = '';
            $info['p_days'] = '';
            $info['week_num'] = 0;
            $info['week_money'] = 0;
        }
        $this->config->load('setup');
        $states = $this->config->item('guest_state');
        $info['state_desc'] = $states[$info['order_state']];
        $this->load->model('Mgames');
        $info['game_name']      = $this->Mgames->get_game_name($info['game_id']);
        $info['area_name']      = $this->Mgames->get_area_name($info['game_area']);
        $info['server_name']    = $this->Mgames->get_server_name($info['game_server']);
        $info['group_name']     = $this->Mgames->get_group_info('en_name',$info['role_group'],'cn_name');
        $info['career_name']    = $this->Mgames->get_career_info('en_name',$info['role_career'],'cn_name');
        return $info;
    }

	function _get_member_order_info($order_id) {
        $this->load->model('Morders');
        $info = $this->Morders->get_order_info($order_id);
        $info['order_discount'] = self::_get_order_discount($order_id);
        $this->load->model('Mproduct');
        $p_info = $this->Mproduct->get_product_info($info['product']);
        if(!empty($p_info)){
            $info['p_name'] = $p_info['p_name'];
            $info['p_days'] = $p_info['p_days'];
            $info['week_num'] = $p_info['week_num'];
            $info['week_money'] = $p_info['week_money'];
        } else {
            $info['p_name'] = '';
            $info['p_days'] = '';
            $info['week_num'] = 0;
            $info['week_money'] = 0;
        }
        $this->config->load('setup');
        $states = $this->config->item('member_state');
        $info['state_desc'] = $states[$info['order_state']];
        $this->load->model('Mgames');
        $info['game_name']      = $this->Mgames->get_game_name($info['game_id']);
        $info['area_name']      = $this->Mgames->get_area_name($info['game_area']);
        $info['server_name']    = $this->Mgames->get_server_name($info['game_server']);
        $info['group_name']     = $this->Mgames->get_group_info('en_name',$info['role_group'],'cn_name');
        $info['career_name']    = $this->Mgames->get_career_info('en_name',$info['role_career'],'cn_name');
        return $info;
    }

    function _get_order_discount($order_id){
    	$this->load->model('Morders');
    	$info = $this->Morders->get_order_discount($order_id);
    	return $info ? $info['discount'] : '0.00';
    }


	/**
	 * 获取订单id
	 * @param $length
	 * @return string
	 */
	function _get_order_id($length=16){
		$str = strval(date('YmdHis'));
		$len = $length-strlen($str);
		for($i=0;$i<$len;$i++){
			$str .= strval(rand(0,9));
		}
		return $str;
	}

}
?>